import axios from 'axios';
import Message from './elementui-message.js';
import { MessageBox } from 'element-ui';
import global from './global.js';
import Vue from 'vue';
import util from './util.js';

let apipre = global.apipre;

let vmuAxios = {
  install: function (Vue, options) {
    const service = axios.create({
      timeout: 30000, // 请求超时时间
      withCredentials: true,
      baseURL: process.env.VUE_APP_baseURL
    })

    service.interceptors.request.use(config => {
      // console.log(Vue.$cookies.get('Authorization'));
      if(Vue.$cookies.get('Authorization') != null){
        config.headers['Authorization'] = Vue.$cookies.get('Authorization');
      }
      return config
    }, error => {
      return Promise.reject(error)
    })

    service.interceptors.response.use((response) => {
      // console.log(response);
      return response
    }, error => {
      return Promise.reject(error)
    })

    let $http = {
      get: function (url, params={}, success, fail=failLocal, error=errorLocal) {
        params.t = new Date().getTime()
        service({
          url: apipre + url,
          method: 'get',
          headers: {},
          params
        }).then(res => {
          if (res.data.code === '200') {
            success(res.data.data)
          } else {
            fail(res.data.msg)
          }
        }).catch((err) => {
          Message.error({message: '抱歉，请求异常，请稍后再试', showClose: true});
          console.log(err);
          error(err)
        })
      },
      getTest: function (url, params = {}) {
        params.t = new Date().getTime()
        return service({
          url: apipre + url,
          method: 'get',
          headers: {},
          params
        })
      },
      post: (url, data={}, success, fail, error, cusParam) => {
        $http.postCusHeader(url, data, {'Content-Type': 'application/json; charset=UTF-8'}, success, fail, error, cusParam)
      },
      postFormInit: (url, data={}, success, fail, error, cusParam) => {
        $http.postCusHeader(url, data, {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, success, fail, error, 
          //保留原值，增加新值, 忽略空值
          {init: true, ...cusParam}
        )
      },
      postFormLoading: (url, data={}, success, fail, error, cusParam) => {
        $http.postCusHeader(url, data, {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, success, fail, error, 
          //保留原值，增加新值, 忽略空值
          {loading:true, ...cusParam}
        )
      },
      postForm: (url, data={}, success, fail, error, cusParam) => {
        $http.postCusHeader(url, data, {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, success, fail, error, cusParam)
      },
      postCusHeader: (url, data={}, headers={}, success=function(){}, fail=failLocal, error=errorLocal, cusParam={}) => {
        // console.log(cusParam);
        if(cusParam.loading){
          util.openLoading();
        }
        service({
          url: apipre + url,
          method: 'post',
          headers,
          transformRequest:[function(data, headers){
            if(data != null){
              if(headers['Content-Type'] && headers['Content-Type'].indexOf('application/x-www-form-urlencoded') >= 0){
                let dataStr = '';
                for(let item in data) {
                  if(data[item] != null){
                    dataStr += encodeURIComponent(item) + '=' + encodeURIComponent(data[item]) + '&';
                  }
                }
                return dataStr.substring(0,dataStr.length-1);
              }else if(headers['Content-Type'] && headers['Content-Type'].indexOf('application/json') >= 0){
                data = JSON.stringify(data);
              }
            }
            return data;
          }],
          data: data
        }).then(res => {
          if(cusParam.loading){
            util.closeLoading();
          }
          if (res.data.code === '200') {
            success(res.data.data)
          } else {
            fail(res.data.code, res.data.msg, cusParam);
          }
        }).catch(err => {
          if(cusParam.loading){
            util.closeLoading();
          }
          Message.error({message: '抱歉，请求异常，请稍后再试', showClose: true});
          console.log(err);
          error(err)
        })
      }
    }

    Vue.prototype.$http = $http
  }
}

function failLocal(code, msg, cusParam){
  if (code === '1001') { // token失效
    let back = false;
    if(cusParam.init){
      back = true;
    }
    MessageBox.confirm(msg+' 是否登录?', '提示', {
      customClass:"el-message-box_custom",
      confirmButtonText: '确定',
      cancelButtonText: back?"返回":"取消",
      type: 'warning'
    }).then(() => {
      location.href = '#/index/login?orginUrl='+encodeURIComponent(location.href);
    }).catch(() => {
      if(back){
        util.goback();
      }
    });
  }
  Message.error(msg);
}

function errorLocal(){
}

export default vmuAxios
